<template>
  <el-dialog v-if="dialogVisiable" v-model="dialogVisiable" title="脚本及参数设置" width="1000px">
    <div v-loading="loading" class="content">
      <el-steps :active="stepActive" align-center>
        <el-step title="选择脚本" />
        <el-step title="脚本参数设置" />
        <el-step title="运行" />
      </el-steps>
      <div v-if="stepActive === 1" class="step-block">
        <div class="block-title">选择脚本</div>
        <el-tabs v-model="activeName">
          <el-tab-pane v-for="(item, index) in datas" :key="'tab-pane-' + index" :label="item.label" :name="item.field">
            <div class="p-2">
              <el-table :data="item.tableDatas" height="200" class="mt-2" @selection-change="handleSelectChange($event, index)">
                <el-table-column width="55" type="selection"></el-table-column>
                <el-table-column label="序号" width="55" type="index"></el-table-column>
                <el-table-column label="脚本名称" min-width="200" prop="name"></el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-if="stepActive !== 1" class="step-block">
        <div v-if="stepActive === 2" class="block-title">脚本参数设置</div>
        <div v-if="stepActive === 3" class="block-title">基本信息</div>
        <div v-if="stepActive === 3" class="form">
          <el-form ref="dialogFormRef" :model="dialogForm" :rules="rules" inline>
            <el-form-item prop="name" label="统计名称：" label-width="100">
              <el-input v-model="dialogForm.name" placeholder="请输入" disabled clearable style="width: 200" />
            </el-form-item>
            <el-form-item label="机型:" prop="aircraft">
              <el-input v-model="dialogForm.aircraft" placeholder="请输入" disabled clearable style="width: 200" />
            </el-form-item>
          </el-form>
        </div>
        <div v-if="stepActive === 3" class="block-title">脚本及参数</div>
        <el-tabs v-model="activeName2">
          <el-tab-pane v-for="(item, index) in datas2" :key="'tab-pane-' + index" :label="item.label" :name="item.field">
            <div v-if="stepActive === 3" class="font-bold pb-2"><span class="color-#f56c6c mr-1">*</span>载荷实验数据</div>
            <el-table v-if="stepActive === 3" :data="item.tableDatas" height="200" class="mt-2">
              <el-table-column label="序号" width="55" type="index"></el-table-column>
              <el-table-column prop="loadExperimentName" label="任务名称" min-width="100" show-overflow-tooltip></el-table-column>
              <el-table-column label="机型" width="80" prop="modelType"></el-table-column>
              <el-table-column label="载荷分类" width="100" prop="loadType"></el-table-column>
              <el-table-column label="阶段" width="80" prop="stage"></el-table-column>
              <el-table-column label="载荷版本" width="100" prop="version"></el-table-column>
              <el-table-column label="轮次" width="100" prop="round"></el-table-column>
            </el-table>
            <div v-if="stepActive === 3" class="font-bold pb-2 pt-2"><span class="color-#f56c6c mr-1">*</span>实验脚本及参数</div>
            <div v-for="(el, i) in item.datas" :key="'script-item' + i" class="mb-2">
              <div class="name">{{ el.name }}</div>
              <div class="params">
                <JsonSchemaElement
                  :ref="(eldata) => setRef(eldata, index, i)"
                  :key="'jse' + index + i"
                  :data="getFormData(el)"
                  :schema="getSchema(el)"
                  :disabled="stepActive === 3"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="stepActive !== 2" :loading="btnLoading" @click="closeDialog">取消</el-button>
        <el-button v-if="stepActive !== 1" :loading="btnLoading" type="primary" @click="prevStep">上一步</el-button>
        <el-button v-if="stepActive !== 3" :loading="btnLoading" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-if="stepActive === 3" :loading="btnLoading" type="primary" @click="runDialog">运行</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="selectScriptParameterDialog" lang="ts">
import JsonSchemaElement from './jsonSchemaElement.vue';
import {
  listConfig,
  genTaskChainParam,
  initTaskChains,
  getTaskWorkspaceDetail,
  runTaskChains
} from '@/api/loadProcessingAlgorithm/experimentResultStatistic/index';
const dialogVisiable = ref(false);
const queryFormRef = ref<ElFormInstance>();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const stepActive = ref(1);
const loading = ref(false);
const btnLoading = ref(false);
const workspaceId = ref('');
const activeName = ref('first');
const activeName2 = ref('first');
const refDatas = ref([]);
const chainRunInfoIds = ref([]);
const datas = ref([
  {
    label: '飞行载荷',
    field: 'first',
    tableDatas: []
  },
  {
    label: '地面载荷',
    field: 'second',
    tableDatas: []
  },
  {
    label: '动载荷',
    field: 'third',
    tableDatas: []
  }
]);
const datas2 = ref([
  {
    label: '飞行载荷',
    field: 'first',
    datas: [],
    tableDatas: []
  },
  {
    label: '地面载荷',
    field: 'second',
    datas: [],
    tableDatas: []
  },
  {
    label: '动载荷',
    field: 'third',
    datas: [],
    tableDatas: []
  }
]);
const emit = defineEmits(['on-refresh']);
const dialogForm = reactive({
  name: '',
  aircraft: ''
});
const initData2 = () => {
  getTaskWorkspaceDetail(workspaceId.value).then((res) => {
    const data = res.data;
    dialogForm.name = data.name;
    dialogForm.aircraft = data.aircraft;
    datas2.value.forEach((element) => {
      const arr = data.relatedExperiments.filter((item) => item.loadName === element.label);
      element.tableDatas = arr;
    });
  });
};
const initData = () => {
  loading.value = true;
  listConfig()
    .then((res) => {
      console.log(res);
      datas.value.forEach((item) => {
        const arr = res.data.filter((el) => el.folder.includes(item.label));
        item.tableDatas = arr;
      });
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};
const handleSelectChange = (val, index) => {
  const obj = datas2.value[index];
  obj.datas = val;
};
const nextStep1 = () => {
  btnLoading.value = true;
  const arr = datas2.value.map((item) => item.datas).flat();
  const obj = {
    workspaceId: workspaceId.value,
    chainParamConfigList: arr
  };
  genTaskChainParam(obj)
    .then((res) => {
      datas2.value.forEach((item) => {
        const arr = res.data.filter((el) => el.folder.includes(item.label));
        item.datas = arr;
        stepActive.value = 2;
      });
      btnLoading.value = false;
    })
    .catch(() => {
      btnLoading.value = false;
    });
};
const nextStep2 = () => {
  btnLoading.value = true;
  const arr = [];
  datas2.value.forEach((item, index) => {
    item.datas.forEach((el, i) => {
      const data = refDatas.value[`jsonSchemaElementRef-${index}-${i}`].getData();
      const element = JSON.parse(JSON.stringify(el));
      element.taskParams.taskChainParam = element.taskParams.taskChainParam.map((e, ind) => {
        e.taskParams = data[ind];
        return e;
      });
      arr.push(element);
    });
  });
  const obj = {
    workspaceId: workspaceId.value,
    runImmediately: false,
    chainParamList: arr
  };
  initTaskChains(obj)
    .then((res) => {
      chainRunInfoIds.value = res.data.map((item) => item.id);
      proxy?.$modal.msgSuccess('初始化任务链成功！');
      btnLoading.value = false;
      stepActive.value = 3;
    })
    .catch(() => {
      btnLoading.value = false;
    });
};
const prevStep = () => {
  stepActive.value -= 1;
};
const runDialog = () => {
  btnLoading.value = true;
  const obj = {
    chainRunInfoIds: chainRunInfoIds.value
  };
  runTaskChains(obj)
    .then((res) => {
      proxy?.$modal.msgSuccess('运行开始！');
      btnLoading.value = false;
      emit('on-refresh');
      closeDialog();
    })
    .catch(() => {
      btnLoading.value = false;
    });
};
const setRef = (el, index, i) => {
  if (el) {
    refDatas.value[`jsonSchemaElementRef-${index}-${i}`] = el;
  }
};
const getFormData = (data) => {
  return data.taskParams.taskChainParam.map((item, index) => {
    return item.taskParams;
  });
};
const getSchema = (data) => {
  return data.taskParamSchemas.properties.taskChainParam.prefixItems.map((item) => {
    return item.properties.taskParams;
  });
};
const closeDialog = () => {
  dialogVisiable.value = false;
};
const nextStep = () => {
  if (stepActive.value === 1) {
    nextStep1();
  } else {
    nextStep2();
  }
};
const openDialog = async (id) => {
  workspaceId.value = id;
  stepActive.value = 1;
  initData();
  initData2();
  dialogVisiable.value = true;
};
defineExpose({
  openDialog
});
</script>

<style lang="scss" scoped>
.block-title {
  color: #1890ff;
  font-size: 14px;
  padding-bottom: 12px;
  display: flex;
  align-items: center;
  margin-left: 8px;
}
.block-title::before {
  content: '';
  width: 3px;
  height: 15px;
  background-color: #48a1f5;
  margin-right: 8px;
}
.name {
  color: #1890ff;
  margin-bottom: 8px;
}
.dialog-footer {
  text-align: center;
}
</style>
